package com.example.onlinemallsystem.controller;

import com.example.onlinemallsystem.entity.Cart;
import com.example.onlinemallsystem.entity.User;
import com.example.onlinemallsystem.service.CartService;
import com.example.onlinemallsystem.util.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.List;

/**
 * 购物车控制器
 * 使用HttpSession获取用户信息
 */
@RestController
@RequestMapping("/Carts")
@CrossOrigin(origins = "http://localhost:5173", allowCredentials = "true")
@Slf4j
public class CartController {

    @Autowired
    private CartService cartService;

    /**
     * 添加商品到购物车
     * @param productId 商品ID
     * @param quantity 购买数量
     * @param session HTTP会话
     * @return 操作结果
     */
    @PostMapping("/add")
    public JsonResult<Long> addToCart(
            @RequestParam Long productId,
            @RequestParam Integer quantity,
            HttpSession session) {
        try {
            Long userId = (Long) session.getAttribute("userId");
            if (userId == null) {
                return new JsonResult<>(401, "未登录，请先登录");
            }
            Long cartId = cartService.addToCart(userId, productId, quantity);
            return new JsonResult<>(200, "添加成功", cartId);
        } catch (RuntimeException e) {
            log.error("添加购物车失败：{}", e.getMessage());
            return new JsonResult<>(400, e.getMessage());
        } catch (Exception e) {
            log.error("添加购物车异常", e);
            return new JsonResult<>(500, "服务器错误");
        }
    }

    /**
     * 更新购物车商品数量
     * @param productId 商品ID
     * @param quantity 新数量
     * @param session HTTP会话
     * @return 操作结果
     */
    @PutMapping("/update/quantity")
    public JsonResult<Boolean> updateQuantity(
            @RequestParam Long productId,
            @RequestParam Integer quantity,
            HttpSession session) {
        try {
            Long userId = (Long) session.getAttribute("userId");
            if (userId == null) {
                return new JsonResult<>(401, "未登录，请先登录");
            }

            boolean result = cartService.updateQuantity(userId, productId, quantity);
            return new JsonResult<>(200, result ? "更新成功" : "更新失败", result);
        } catch (RuntimeException e) {
            log.error("更新购物车数量失败：{}", e.getMessage());
            return new JsonResult<>(400, e.getMessage());
        } catch (Exception e) {
            log.error("更新购物车数量异常", e);
            return new JsonResult<>(500, "服务器错误");
        }
    }

    /**
     * 切换商品选中状态
     * @param productId 商品ID
     * @param selected 选中状态(1-选中, 0-未选中)
     * @param session HTTP会话
     * @return 操作结果
     */
    @PutMapping("/update/selected")
    public JsonResult<Boolean> updateSelected(
            @RequestParam Long productId,
            @RequestParam Integer selected,
            HttpSession session) {
        try {
            Long userId = (Long) session.getAttribute("userId");
            if (userId == null) {
                return new JsonResult<>(401, "未登录，请先登录");
            }

            boolean result = cartService.updateSelected(userId, productId, selected);
            return new JsonResult<>(200, result ? "更新成功" : "更新失败", result);
        } catch (RuntimeException e) {
            log.error("更新选中状态失败：{}", e.getMessage());
            return new JsonResult<>(400, e.getMessage());
        } catch (Exception e) {
            log.error("更新选中状态异常", e);
            return new JsonResult<>(500, "服务器错误");
        }
    }

    /**
     * 删除购物车商品
     * @param productId 商品ID
     * @param session HTTP会话
     * @return 操作结果
     */
    @DeleteMapping("/delete")
    public JsonResult<Boolean> deleteCartItem(
            @RequestParam Long productId,
            HttpSession session) {
        try {
            Long userId = (Long) session.getAttribute("userId");
            if (userId == null) {
                return new JsonResult<>(401, "未登录，请先登录");
            }

            boolean result = cartService.deleteCartItem(userId, productId);
            return new JsonResult<>(200, result ? "删除成功" : "删除失败", result);
        } catch (RuntimeException e) {
            log.error("删除购物车失败：{}", e.getMessage());
            return new JsonResult<>(400, e.getMessage());
        } catch (Exception e) {
            log.error("删除购物车异常", e);
            return new JsonResult<>(500, "服务器错误");
        }
    }


    /**
     * 查询用户购物车列表
     * @param session HTTP会话
     * @return 购物车列表
     */
    @GetMapping("/list")
    public JsonResult<List<Cart>> listCartItems(HttpSession session) {
        try {
            Long userId = (Long) session.getAttribute("userId");
            if (userId == null) {
                return new JsonResult<>(401, "未登录，请先登录");
            }

            List<Cart> cartItems = cartService.listCartItems(userId);
            return new JsonResult<>(200, "查询成功", cartItems);
        } catch (Exception e) {
            log.error("查询购物车列表异常", e);
            return new JsonResult<>(500, "服务器错误");
        }
    }

    /**
     * 计算选中商品总价
     * @param session HTTP会话
     * @return 总价
     */
    @GetMapping("/total")
    public JsonResult<Long> calculateTotal(HttpSession session) {
        try {
            Long userId = (Long) session.getAttribute("userId");
            if (userId == null) {
                return new JsonResult<>(401, "未登录，请先登录");
            }

            Long total = cartService.calculateSelectedTotal(userId);
            return new JsonResult<>(200, "计算成功", total);
        } catch (Exception e) {
            log.error("计算总价异常", e);
            return new JsonResult<>(500, "服务器错误");
        }
    }
}